package com.health.system.common.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.health.system.common.exception.JsonConvertException;
import com.health.system.common.exception.JsonWriteException;

import javax.servlet.ServletInputStream;
import java.io.IOException;
import java.util.Map;

/**
 */
public class JsonUtil {
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private JsonUtil() {

    }

    public static <T> T convert(String json, Class<T> curClass) {
        try {
            return OBJECT_MAPPER.readValue(json, curClass);
        } catch (JsonProcessingException e) {
            throw new JsonConvertException(e);
        }
    }

    public static Map<String, String> convert(String json) {
        try {
            return OBJECT_MAPPER.readValue(json, new TypeReference<Map<String, String>>() {
            });
        } catch (JsonProcessingException e) {
            throw new JsonConvertException(e);
        }
    }

    public static Map<String, String> convert(ServletInputStream input) {
        try {
            return OBJECT_MAPPER.readValue(input, new TypeReference<Map<String, String>>() {
            });
        } catch (IOException e) {
            throw new JsonConvertException(e);
        }
    }

    public static String writer(Object data) {
        try {
            return OBJECT_MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            throw new JsonWriteException(e);
        }
    }
}
